using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Sustainalytics.Synchronization.Validation.Restore
{
    public class SyncLogProfileRestoreHandlerDecorator : IProfileRestoreHandler
    {
        private readonly Func<IProfileRestoreHandler> handlerFactory;

        private Action<string> syncLoggingAction; 

        public SyncLogProfileRestoreHandlerDecorator(Func<IProfileRestoreHandler> handlerFactory)
        {
            this.handlerFactory = handlerFactory;
        }

        public void SetLoggingOutput(Action<string> action)
        {
            syncLoggingAction = action;
        }

        public async Task ForEachElementsAsync(InvalidCompaniesList companyIds)
        {
            var decoratedHandler = handlerFactory();
            var entityTypeName = decoratedHandler.GetType().GetGenericArguments().FirstOrDefault().FullName;
            syncLoggingAction.Invoke("START - " + entityTypeName);
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            await decoratedHandler.ForEachElementsAsync(companyIds).ConfigureAwait(false);
            stopwatch.Stop();
            syncLoggingAction.Invoke("FINISHED - " + entityTypeName + " in " + stopwatch.Elapsed);
        }
    }
}